#include "screen.h"
#include "ball.h"
#include "line.h"

#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>

#include <stdio.h>

using namespace std;

bool end = false;

struct Gameplay {
	Screen* s;
	Ball* b;
	Line* r;
	Line* l;
};

int getch( ) {
	struct termios oldt, newt;
	int ch;
	
	tcgetattr( STDIN_FILENO, &oldt );
	
	newt = oldt;
	newt.c_lflag &= ~( ICANON | ECHO );
	
	tcsetattr( STDIN_FILENO, TCSANOW, &newt );
	ch = getchar();
	tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
	
	return ch;
}

void* print( void* arg ) {
	try{
		while( 1 ) {
				((Gameplay*)arg)->s->print();
				((Gameplay*)arg)->b->update();
				usleep( 100000 );
		}
	} catch(const char* w) {
		printf("%s", w);
	}
	
	throw "aa";
	return NULL;
}

int main() {
	Gameplay g;
	
	Screen screen;
	g.s = &screen;
	
	Ball ball( &screen );
	g.b = &ball;
	ball.update();
	
	Line left( &screen, true );
	g.l = &left;
	
	Line right( &screen, false );
	g.r = &right;
	
	pthread_t printThread;
	
	pthread_create( &printThread, NULL, print, &g );

	while(!end) {
		char k = (char)getch();
		if( k == 'q' ) {
			left.move( Line::UP );
		} else if( k == 'a' ) {
			left.move( Line::DOWN );
		}
		
		if( k == 'p' ) {
			right.move( Line::UP );
		} else if( k == 'l' ) {
			right.move( Line::DOWN );
		}
	}
	
	pthread_join ( printThread, NULL );
}
